//
//  YJViewController.m
//  练习
//
//  Created by hcios on 2017/7/5.
//  Copyright © 2017年 hcios. All rights reserved.
//

#import "YJViewController.h"
#import "YJCollectionViewCell.h"
#import "YJModel.h"

#import "AFNetworking.h"
#import "MJRefresh.h"
#import "SDCycleScrollView.h"

#import "YJWebViewController.h"
#import "UserViewController.h"
#import "YJResultViewController.h"



@interface YJViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,YJCollectionViewCellDelegate,SDCycleScrollViewDelegate>{
    
    NSInteger page;
    
}

@property (nonatomic,strong) UICollectionView *cardView;
@property (nonatomic,strong) NSMutableArray *dataArr;

@end

static NSString *headerViewIdentifier = @"headerview";
static NSString *const CollectionViewCellIdentifier = @"cellID";

@implementation YJViewController

-(instancetype)init{
    self = [super init];
    if (self) {
        _dataArr = [[NSMutableArray alloc] init];
        page = 1;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initCollectionView];
    
//    [self netWorking];
    [_cardView.mj_header beginRefreshing];
}

-(void)initCollectionView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个cell大小
    layout.itemSize = CGSizeMake(SCREEN_WIDTH - 20, 210);
    //每个cell之间的距离
    layout.minimumLineSpacing = 10.0f;
    
    layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH - 20, 180);
    
    self.cardView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 112) collectionViewLayout:layout];
    self.cardView.delegate = self;
    self.cardView.dataSource = self;
    self.cardView.showsVerticalScrollIndicator = NO;
    
    //注册cell
    [self.cardView registerClass:[YJCollectionViewCell class] forCellWithReuseIdentifier:@"cellID"];
    self.cardView.backgroundColor = [UIColor colorWithRed:214 / 255.0f green:226 / 255.0f blue:238 / 255.0f alpha:1.0];
    
    //注册header
    [self.cardView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];
  
    //刷新
    __weak typeof(self) weakSelf = self;
    self.cardView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf isRefreshData:YES];
    }];
    self.cardView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf isRefreshData:NO];
    }];
    [self.view addSubview:self.cardView];
}


-(void)isRefreshData:(BOOL)isRefresh{
    
    isRefresh ? page = 1 : page++;
    
    NSLog(@"当前页面数量 ：%ld",(long)page);
    
    NSString *urlString = @"http://chanyouji.com/api/trips/featured.json";
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:@(page) forKey:@"page"];
    
    //网络请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:urlString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = responseObject;
        if (isRefresh) {
            [_dataArr removeAllObjects];
            self.cardView.mj_footer.state = MJRefreshStateIdle;
        }
        if ([dict count] > 0) {
            for (NSDictionary *dict in responseObject) {
                //取值
                YJModel *model = [[YJModel alloc] initWithDict:dict];
                [_dataArr addObject:model];
            }
        }
        if ([dict count] < 10) {
            [self.cardView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.cardView reloadData];
        if (!isRefresh && [dict count] == 0) {
            [self.cardView.mj_footer endRefreshingWithNoMoreData];
        }else [self endRefresh];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络请求失败");
    }];
}

-(void)endRefresh{
    if (page == 1) {
        [self.cardView.mj_header endRefreshing];
    }else {
        [self.cardView.mj_footer endRefreshing];
    }
}




#pragma mark - 数据源方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArr.count;;
}


-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YJCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCellIdentifier forIndexPath:indexPath];

    cell.model = _dataArr[indexPath.row];
    cell.delegate = self;
    return cell;
    
}


-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
}


#pragma mark - collectionViewHeader
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
    
    NSArray *imageUrl = @[@"http://images4.c-ctrip.com/target//100l0a00000055lfj4721.jpg",@"http://p.chanyouji.cn/203484/1450780368182p1a74jv78j5pofs1fd6r8k14sj2.jpg"];
    
    SDCycleScrollView *scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 20, 180) imageNamesGroup:imageUrl];
    
    scrollView.delegate = self;
    
    scrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    scrollView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    scrollView.layer.masksToBounds = YES;
    scrollView.layer.cornerRadius = 4;
    
    [header addSubview:scrollView];
    
    return header;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH - 20, 170);
    }else return CGSizeZero;
}




-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld%ld",(long)[indexPath section],(long)[indexPath row]);
    YJResultViewController *VC = [[YJResultViewController alloc] init];
    YJModel *model = [[YJModel alloc] init];
    model = _dataArr[indexPath.row];
    VC.userID = model.userID;
    VC.backImgUrl = model.yj_front_cover_photo_url;
    VC.userImgUrl = model.user_image_url;
    VC.nameText = model.yj_name;
    VC.dayText = model.yj_start_date;
    VC.selfID = model.selfID;
    [self.navigationController pushViewController:VC animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}

#pragma mark - cell的代理方法
-(void)gesAuthor:(UITapGestureRecognizer *)ges{
    NSLog(@"%@",ges);
    //获取作者信息的indexpath
    UIButton *btn = (UIButton *)ges;
    CGPoint point = btn.center;
    point = [self.cardView convertPoint:point fromView:btn.superview];
    NSIndexPath *indexPath = [self.cardView indexPathForItemAtPoint:point];
    UserViewController *VC = [[UserViewController alloc] init];
    YJModel *model = _dataArr[indexPath.row];
    VC.userID = model.userID;
    VC.userName = model.user_name;
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - SDCycleScrollViewDelegate
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    if (index == 0) {
        YJWebViewController *VC = [[YJWebViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
    }else{
    
    NSLog(@"点击第%ld张轮播图",index);
    }
}







@end
